package com.feng.common.spring;

import com.feng.common.exception.ErrorCode;
import com.feng.common.exception.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

/**
 * @author Lee
 */
public class ApplicationContextHolder implements ApplicationContextAware {

    private final static Logger LOGGER = LoggerFactory.getLogger(ApplicationContextHolder.class);

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (ApplicationContextHolder.applicationContext != null){
            LOGGER.info("上下文信息被覆盖，原有上下文：{}",ApplicationContextHolder.applicationContext);
        }
        ApplicationContextHolder.applicationContext = applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName){
        assertApplicationContextIsNotNull();
        return (T) applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> clazz){
        assertApplicationContextIsNotNull();
        return applicationContext.getBean(clazz);
    }

    public static <T> Map<String,T> getBeans(Class<T> clazz){
        assertApplicationContextIsNotNull();
        return applicationContext.getBeansOfType(clazz);
    }

    /**
     * 检查上下文信息不能为空
     */
    private static void assertApplicationContextIsNotNull (){
        if (ApplicationContextHolder.applicationContext == null) {
            LOGGER.error("上下文信息为空");
            throw new ValidationException(ErrorCode.SystemError,"上下文信息为空");
        }
    }


}
